package com.baitengsoft.patentapimonitor.api.service.impl;

import com.baitengsoft.patentapimonitor.api.dao.PacApplicantDao;
import com.baitengsoft.patentapimonitor.api.dao.WebPlatFormAreaDao;
import com.baitengsoft.patentapimonitor.api.entity.WebPlatformareaEntity;
import com.baitengsoft.patentapimonitor.api.model.WebAreaInfo;
import com.baitengsoft.patentapimonitor.api.service.CfgPatentIndicatorService;
import com.baitengsoft.patentapimonitor.api.service.WebPlatformareaService;
import com.baitengsoft.patentapimonitor.common.utils.DateUtils;
import com.baitengsoft.patentapimonitor.common.utils.PageResult;
import com.baitengsoft.patentapimonitor.common.utils.Res;
import com.baitengsoft.patentapimonitor.common.utils.SearchParam;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by QEK on 2017/12/14.
 */
@Service("web_platformareaService")
public class WebPlatformareaServiceImpl extends BaseServiceImpl<WebPlatformareaEntity> implements WebPlatformareaService {

    @Autowired
    private WebPlatFormAreaDao platformareaDao;
    @Autowired
    private PacApplicantDao pacApplicantDao;
    @Autowired
    private CfgPatentIndicatorService cfgPatentIndicatorService;

    @Override
    public WebPlatformareaEntity selectAreaById(Integer id) {

        return platformareaDao.selectAreaById(id);
    }

    /**
     * 删除区域。注意：删除后原先归属的数据需要处理到未分类当中
     * @param id
     * @return
     */
    @Override
    public int deleteAreaById(Integer id) {
        int result = platformareaDao.deleteAreaById(id);
        if(result > 0){
            //删除成功之后，把权利人之前选好的区域修改成未分类（0代表未分类）
            pacApplicantDao.updateAreaIdToZero(id);
            //删除成功之后，把当年指标删除
            cfgPatentIndicatorService.deleteByAreaIdAndYearYM(id,DateUtils.getCurrentYear());
        }
        return result;
    }

    @Override
    public Res updateArea(WebPlatformareaEntity entity) {
        WebPlatformareaEntity result = platformareaDao.selectByPrimaryKey(entity.getId());
        if (result == null) return Res.error("参数有误：未查询到相关区域");
        result.setName(entity.getName());
        result.setUpdatedate(new Date());
        result.setUpdateoperid(entity.getUpdateoperid());
        if (entity.getSort() == null || entity.getSort()<1){
            return Res.error("参数有误：序号必须大于0");
        }
        if (!entity.getSort().equals(result.getSort()) && !checkSortIsExitByPlatformId(entity.getPlatformid(), entity.getSort()))
            return Res.error("参数有误：序号已存在");
        int updateArea = platformareaDao.updateArea(entity);
        if(updateArea == 1){
            return Res.ok("修改成功！");
        }
        return Res.error("修改失败！");

    }

    @Override
    public Res addAreaByPlatformId(WebPlatformareaEntity entity) {
        if(!checkSortIsExitByPlatformId(entity.getPlatformid(),entity.getSort())){
            return Res.error("参数有误：序号已存在");
        }
        if (entity.getSort() == null || entity.getSort()<1){
            return Res.error("参数有误：序号必须大于0");
        }
        if(IsExist(entity.getName(),entity.getPlatformid())){
            return Res.error("该区域已存在");
        }
        //查询删除的区域是否有一样名字的区域
        Example example = new Example(WebPlatformareaEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status",-1);
        criteria.andEqualTo("name",entity.getName());
        criteria.andEqualTo("platformid",entity.getPlatformid());
        List<WebPlatformareaEntity> entities = platformareaDao.selectByExample(example);
        if (entities!=null && entities.size()>0){
            WebPlatformareaEntity entity1 = entities.get(0);
            entity1.setStatus(1);
            entity1.setSort(entity.getSort());
            int i = platformareaDao.updateByPrimaryKey(entity1);
            //添加成功后初始化当年指标数据
            cfgPatentIndicatorService.initIndicatorByAreaIdAndDateYM(entity1.getId(),DateUtils.getCurrentYear());
            return Res.ok("添加成功！");
        }
        entity.setStatus(1);
        int result = platformareaDao.insert(entity);
        if(result == 1){
            //添加成功后初始化当年指标数据
            cfgPatentIndicatorService.initIndicatorByAreaIdAndDateYM(entity.getId(),DateUtils.getCurrentYear());
            return Res.ok("添加成功！");
        }
        return Res.error("添加失败！");
    }

    @Override
    public PageResult<WebPlatformareaEntity> pageSelectAreas(Integer platformId, SearchParam searchParam) {
        Mapper<WebPlatformareaEntity> mapper = this.getMapper();
        Example example = new Example(WebPlatformareaEntity.class);
        //查询当前平台的数据
        Example.Criteria c = example.createCriteria();
        c.andEqualTo("platformid",platformId);
        c.andEqualTo("status",1);
        //查询条数
        int count = mapper.selectCountByExample(example);
        //排序
        example.orderBy("sort").asc();
        RowBounds rb = new RowBounds(searchParam.getPageNumber(),searchParam.getPageSize());
        List<WebPlatformareaEntity> list = mapper.selectByExampleAndRowBounds(example,rb);
        return new PageResult<WebPlatformareaEntity>(list,searchParam.getPageNumber(),searchParam.getPageSize(),count);
    }

    @Override
    public Integer savePlatformarea(WebPlatformareaEntity entity) {
        return saveByNotNull(entity);
    }

    @Override
    public Integer updatePlatformArea(WebPlatformareaEntity entity) {
        return updateByNotNull(entity);
    }

    @Override
    public List<WebPlatformareaEntity> searchByPlatformId(Integer platformId) {

        Mapper<WebPlatformareaEntity> mapperTk=getMapper();
        Example example=new Example(WebPlatformareaEntity.class);
        Example.Criteria criteria=example.createCriteria();
        criteria.andNotEqualTo("status",-1);
        criteria.andEqualTo("platformid",platformId);
        List<WebPlatformareaEntity> entities=mapperTk.selectByExample(example);
        if(entities!=null&&entities.size()>0) return entities;
        return null;
    }

    /**
     * 只获取指定平台下的区域名称与id
     */
    @Override
    public List<WebAreaInfo> getNameAndIdByPlatformId(Integer platformId) {
        List<WebPlatformareaEntity> entities = platformareaDao.selectAreaByPlatformId(platformId);
        List<WebAreaInfo> webAreaInfos = new ArrayList<>();
        for(WebPlatformareaEntity entity : entities){
            WebAreaInfo info = new WebAreaInfo();
            info.setAreaName(entity.getName());
            info.setAreaId(entity.getId());
            webAreaInfos.add(info);
        }
        return webAreaInfos;
    }

    /**
     * 根据平台Id查询区域IdList
     */
    @Override
    public List<Integer> getAreaIdsByPlatformId(Integer platformid) {
        if (platformid == null || platformid<1) return new ArrayList<>();
        return platformareaDao.selectAreaIdByPlatFormId(platformid);
    }

    /**
     * 判断指定平台是否设置区域
     * 区域为null false
     */
    @Override
    public boolean checkHasAreaByPlatormId(Integer platformid) {
        List<Integer> integers = platformareaDao.selectAreaIdByPlatFormId(platformid);
        return !(integers == null || integers.size() == 0);
    }

    /**
     *  判断指定平台是否设置区域的排序
     * @return true 可以修改 false 不能修改提示已存在排序
     */
    @Override
    public boolean checkSortIsExitByPlatformId(Integer platformid, Integer sort) {
        if (sort == null || platformid == null) return false;
        int count = platformareaDao.selectSortByPlatformId(platformid,sort);
        return count == 0;
    }

    /**
     * 新增、修改之前判断区域是否已经存在
     * @param name
     * @return
     */
    private boolean IsExist(String name,Integer platformId) {
        Mapper<WebPlatformareaEntity> mapper = this.getMapper();
        Example example = new Example(WebPlatformareaEntity.class);
        example.createCriteria().andEqualTo("platformid",platformId).andEqualTo("name",name).andEqualTo("status",1);
        List<WebPlatformareaEntity> list = mapper.selectByExample(example);
        if(list.size() > 0){
            return true;
        }
        return false;
    }



}
